#!/bin/bash

rq=$(date -d '1 days ago' '+%F')
log_dir="/root/hive_data"

echo "日期为： $rq"

execute_hive_script() {
    local script_name=$1
    local log_name=$2
    local task_name=$3

    echo "开始执行${task_name}。"

    # 执行Hive脚本
    nohup hive --hivevar ETL_DATE="$rq" -f "/root/hive_data/${script_name}" > "${log_dir}/${log_name}" 2>&1
    local exit_code=$?

    if (( exit_code == 0 ))
    then
        echo "${task_name}执行结束。"
        return 0
    else
        echo "${task_name}执行异常，请检查日志：${log_dir}/${log_name}"
        return 1
    fi
}

# 顺序执行三个任务
execute_hive_script "fxq-full_inc_add_byDay.sql" "fxq_dwd.log" "反洗钱数抽取曾量脚本" || exit 1
execute_hive_script "fxq_full_byDay.sql" "fxq_dwd_.log" "反洗钱数据全量抽取脚本" || exit 1

echo "所有反洗钱数据增量抽取脚本执行完成。"

echo "将ORC格式转换为文本格式"
echo "开始创建临时表"
nohup hive -f /root/hive_data/ADS临时表.sql > "${log_dir}/createTmp.txt" 2>&1 &
if (( exit_code == 0 ))
    then
        echo "临时表创建成功。"
    else
        echo "临时表创建异常，请检查日志：${log_dir}/createTmp.txt"
        exit
fi

echo "开始导出数据"

read -p "请输入你的Oracle地址：" ora_ip
read -p "请输入你的Oracle用户名：" ora_username
read -p "请输入你的Oracle密码：" ora_pwd

# Sqoop导出函数
execute_sqoop_export() {
    local table_name=$1
    local hdfs_path=$2
    local task_name=$3

    echo "开始导出 ${task_name}..."

    sqoop export \
    --connect jdbc:oracle:thin:@"$ora_ip":1521:orcl \
    --username "$ora_username" \
    --password "$ora_pwd" \
    --table "$table_name" \
    --export-dir "$hdfs_path" \
    --input-fields-terminated-by '\001' \
    --input-lines-terminated-by '\n' \
    --input-null-string '\\\\N' \
    --input-null-non-string '\\\\N' \
    -m 1

    local exit_code=$?

    if (( exit_code == 0 ))
    then
        echo "${task_name} 导出成功。"
        return 0
    else
        echo "${task_name} 导出失败。"
        return 1
    fi
}

# 批量执行Sqoop导出
export_tasks=(
    "CUSTOMER_RISK_OVERVIEW:/user/hive/warehouse/ads.db/customer_risk_overview_tmp_table:客户风险概览"
    "TRANSACTION_RISK_REPORT:/user/hive/warehouse/ads.db/transaction_risk_report_tmp_table:交易风险报告"
    "COMPLIANCE_MONTHLY_REPORT:/user/hive/warehouse/ads.db/compliance_monthly_report_tmp_table:监管合规报告"
    "ALERT_RULE_PERFORMANCE:/user/hive/warehouse/ads.db/alert_rule_performance_tmp_table:预警规则效能分析"
)

for task in "${export_tasks[@]}"; do
    IFS=':' read -r table_name hdfs_path task_name <<< "$task"
    execute_sqoop_export "$table_name" "$hdfs_path" "$task_name" || exit 1
done

echo "所有数据导出任务完成。"